//
//  NetworkTool.m
//  MyLifeApp
//
//  Created by 李杭玖 on 16/10/18.
//  Copyright © 2016年 我家生活科技有限公司. All rights reserved.
//

#import "NetworkTool.h"

@implementation NetworkTool

+(instancetype)sharedTools{
    static NetworkTool *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NetworkTool alloc]initWithBaseURL:nil];
        // 配置网络数据解析方式
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain",nil];
    });
    return instance;
}
// 封装网络请求方法
-(void)requestMethod:(requestMethod)method URL:(NSString *)url parameters:(id)parameters finish:(callBackBlock)finished{
//    ////NSLog(@"URL == %@ parameters == %@", url, parameters);
    if (method == GET) {
        [self GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            finished(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            ////NSLog(@"%@",error);
            finished(nil,error);
        }];
    }else if(method == POST){
        
        self.requestSerializer=[AFJSONRequestSerializer serializer];
        
        [self POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            finished(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            ////NSLog(@"%@",error);
            finished(nil,error);
        }];
    }
}

-(void)requestURL:(NSString *)url withParams:(NSMutableDictionary *)params fileData:(NSMutableDictionary *)fileDic finished:(void (^)(id, NSError *))finished{
    [self POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (fileDic) {
            [formData appendPartWithFileData:fileDic[@"data"]
                                        name:fileDic[@"nameKey"]
                                    fileName:fileDic[@"fileName"]
                                    mimeType:fileDic[@"fileType"]];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ////NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        finished(responseObject,nil);
        ////NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(nil,error);
        ////NSLog(@"%@",error);
    }];
}
@end
